//
//  ComposedViewController.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/16.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    ///表情键盘
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
        
    }
    //MARK: - 监听方法
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        
        textView.resignFirstResponder()
    }
    ///发布微博
    @objc private func sendStatus() {
        let text = textView.emoticonText
        SVProgressHUD.show()
//        let image = UIImage(named: "123")
        
        NetworkTools.sharedTools.sendStatus(text, image: picturePickerController.pictures.last) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: .Gradient)
                return
            }
            SVProgressHUD.showInfoWithStatus("发布成功")
            delay(0.25, callFunc: { () -> () in
                
                self.close()
            })
        }
    }
    
    //表情键盘
    @objc private func selectEmoticon() {
        textView.resignFirstResponder()
        
        textView.inputView = emoticonView
        
        textView.becomeFirstResponder()
    }
    ///选择图片
    @objc private func selectPicture() {
       print(picturePickerController.view.frame)
        
        textView.resignFirstResponder()
        
        if picturePickerController.view.bounds.height > 0{
            return
        }
        
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
//            make.height.equalTo(view.snp_height).multipliedBy(0.6)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(snp_topLayoutGuideBottom)
            make.bottom.equalTo(picturePickerController.view.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //MARK: - 生命周期方法
    override func loadView() {
        view = UIView()
        
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if picturePickerController.view.bounds.height == 0{
            textView.becomeFirstResponder()
        }
    }
    //MARK: - 键盘处理
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //键盘监听方法，调整toolbar位置
    @objc private func keyboardChanged(n: NSNotification) {
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -view.bounds.height + rect.origin.y
        
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
//        let anim = toolbar.layer.animationForKey("position")

    }

    //MARK: - 懒加载控件
    private lazy var toolbar = UIToolbar()
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        //始终可以纵向滚动
        tv.alwaysBounceVertical = true
        //滚动关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置代理
        tv.delegate = self
        return tv
    }()
    private lazy var placeHolderLabel = UILabel(title: "分享新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var picturePickerController = PicturePickerViewController()

}
//textView代理
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}

private extension ComposeViewController {
    //设置界面
    func setupUI() {
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNavigationBar()
        prepareToolbar()
        prepareTextView()
        preparePicturePicker()
        
    }
    ///设置picturePicker
    func preparePicturePicker() {
        //添加自控制器
        addChildViewController(picturePickerController)
        //添加视图
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(0)
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
        }
    }
    ///设置textView
    func prepareTextView() {
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(snp_topLayoutGuideBottom)
            make.bottom.equalTo(toolbar.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
        }
//        textView.text = "分享新鲜事..."
        //占位标签
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    ///设置工具条
    func prepareToolbar() {
        view.addSubview(toolbar)
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in  itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, actionName: dict["actionName"], target: self)
            
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    //设置导航栏
    func prepareNavigationBar() {
        //左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        //标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLabel = UILabel(title:UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "", color: UIColor.lightGrayColor(), fontSize: 13)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
        navigationItem.titleView = titleView
    }
}
